<%
local api = require "luci.passwall2.api"
-%>

<script type="text/javascript">
	//<![CDATA[
	function ajax_add_node(link, group) {
		const chunkSize = 1000;  // Fragmented sending to overcome uhttpd's limitations, with each fragment containing 1000 characters.
		const totalChunks = Math.ceil(link.length / chunkSize);
		let currentChunk = 0;

		function sendNextChunk() {
			if (currentChunk < totalChunks) {
				const chunk = link.substring(currentChunk * chunkSize, (currentChunk + 1) * chunkSize);
				const xhr = new XMLHttpRequest();
				xhr.open('POST', '<%=api.url("link_add_node")%>', true);
				xhr.onload = function () {
					if (xhr.status === 200) {
						currentChunk++;
						sendNextChunk();
					} else {
						alert("<%:Error%>");
						return;
					}
				};
				xhr.onerror = function () {
					alert("<%:Network Error%>");
					return;
				};
				const formData = new FormData();
				formData.append("chunk", chunk);
				formData.append("chunk_index", currentChunk);
				formData.append("total_chunks", totalChunks);
				formData.append("group", group);
				xhr.send(formData);
			} else {
				window.location.href = '<%=api.url("node_list")%>';
			}
		}
		sendNextChunk();
	}
	
	function open_add_link_div() {
		document.getElementById("add_link_div").style.display = "block";
		document.getElementById("nodes_link").focus();
	}
	
	function close_add_link_div() {
		document.getElementById("add_link_div").style.display = "none";
	}
	
	function add_node() {
		var nodes_link = document.getElementById("nodes_link").value;
		var group = (document.querySelector('#addlink_group_custom input[type="hidden"]')?.value || "default");
		nodes_link = nodes_link.replace(/\t/g, "").replace(/\r\n|\r/g, "\n").replace(/<[^>]*>/g, '').trim();
		if (nodes_link != "") {
			var s = nodes_link.split('://');
			if (s.length > 1) {
				ajax_add_node(nodes_link, group);
			}
			else {
				alert("<%:Please enter the correct link.%>");
			}
		}
		else {
			document.getElementById("nodes_link").focus();
		}
	}
	
	function clear_all_nodes() {
		if (confirm('<%:Are you sure to clear all nodes?%>') == true){
			XHR.get('<%=api.url("clear_all_nodes")%>', null,
			function(x, data) {
				if(x && x.status == 200) {
					window.location.href = '<%=api.url("node_list")%>';
				}
				else {
					alert("<%:Error%>");
				}
			});
		}
	}
	
	function add_new_node() {
		window.location.href = '<%=api.url("add_node")%>?redirect=1';
	}
	

	// Custom group dropdown list events
	document.addEventListener("DOMContentLoaded", function() {
		var dropdown = document.getElementById("addlink_group_custom");
		if (!dropdown) return;

		var display = dropdown.querySelector(".selected-display");
		var displayText = display.querySelector(".text");
		var list = dropdown.querySelector(".dropdown-list");
		var hidden = dropdown.querySelector('input[type="hidden"]');
		var input = dropdown.querySelector(".create-item-input");

		display.addEventListener("click", function() {
			list.style.display = list.style.display === "none" ? "block" : "none";
			input.value = "";
			input.focus();
		});

		function selectItem(li) {
			list.querySelectorAll(".dropdown-item").forEach(function(el){
				el.classList.remove("selected");
			});
			li.classList.add("selected");
			hidden.value = li.dataset.value;
			displayText.textContent = li.dataset.value || "<%:default%>";
			list.style.display = "none";
		}

		list.addEventListener("click", function(e){
			var li = e.target.closest(".dropdown-item");
			if (!li || li.classList.contains("custom-input")) return;
			selectItem(li);
		});

		input.addEventListener("keydown", function(e){
			if (e.keyCode !== 13) return;
			e.stopPropagation();
			e.preventDefault();

			var val = input.value.trim();
			if (!val) return;

			if (val.toLowerCase() === "default") {
				var emptyLi = Array.from(list.querySelectorAll(".dropdown-item"))
					.find(function(el){ return !el.dataset.value; });
				if (emptyLi) selectItem(emptyLi);
				input.value = "";
				return;
			}

			var li = Array.from(list.querySelectorAll(".dropdown-item")).find(function(el){
				return el.dataset.value.toLowerCase() === val.toLowerCase();
			});
			if (!li) {
				li = document.createElement("li");
				li.className = "dropdown-item";
				li.dataset.value = val;
				li.textContent = val;
				list.insertBefore(li, input.parentNode); 
			}

			input.value = "";
			selectItem(li);
		});
		// Read group names from tab
		var observer = new MutationObserver(function(mutations, obs){
			var tabs = document.querySelectorAll(".cbi-tabmenu li");
			if(!tabs.length) return;

			tabs.forEach(function(li){
				var group = li.id.split('.').pop();
				if(group === "default") return;
				if(Array.from(list.querySelectorAll(".dropdown-item")).some(el => el.dataset.value === group)) return;

				var newLi = document.createElement("li");
				newLi.className = "dropdown-item";
				newLi.dataset.value = group;
				newLi.textContent = group;

				list.insertBefore(newLi, input.parentNode);
			});

			obs.disconnect();
		});
		observer.observe(document.body, {childList: true, subtree: true});

		// Automatically collapses when clicking on the outside.
		document.addEventListener("click", function(e) {
			if (!dropdown.contains(e.target)) {
				list.style.display = "none";
			}
		});
	});

	//]]>
</script>

<div id="add_link_div">
	<div id="add_link_modal_container">
		<h3><%:Add the node via the link%></h3>
		<div class="value-custom">
			<textarea id="nodes_link" rows="10"></textarea>
			<p id="nodes_link_text"><%:Enter share links, one per line. Subscription links are not supported!%></p>
		</div>
		<div class="value-custom">
			<div class="value-field-custom">
				<label class="value-title-custom" for="addlink_group_custom"><%:Group Name%></label>
				<div id="addlink_group_custom" class="custom-dropdown">
					<div class="selected-display">
						<span class="text"><%:default%></span>
						<span class="arrow">▾</span>
					</div>
					<ul class="dropdown-list" style="display:none;">
						<li class="dropdown-item" data-value=""><%:default%></li>
						<li class="dropdown-item custom-input">
							<input type="text" placeholder="-- <%:custom%> --" class="create-item-input">
						</li>
					</ul>
					<input type="hidden" name="addlink_group" value="">
				</div>
			</div>
		</div>
		<div id="add_link_button_container">
			<input class="btn cbi-button cbi-button-add" type="button" onclick="add_node()" value="<%:Add%>" />
			<input class="btn cbi-button cbi-button-remove" type="button" onclick="close_add_link_div()" value="<%:Close%>" />
		</div>
	</div>
</div>

<div class="pw-toolbar">
	<div class="pw-toolbar-field">
		<input class="btn cbi-button cbi-button-add" type="button" onclick="add_new_node()" value="<%:Add%>" />
		<input class="btn cbi-button cbi-button-add" type="button" onclick="open_add_link_div()" value="<%:Add the node via the link%>" />
		<input class="btn cbi-button cbi-button-remove" type="button" onclick="clear_all_nodes()" value="<%:Clear all nodes%>" />
		<input class="btn cbi-button cbi-button-remove" type="button" onclick="delete_select_nodes()" value="<%:Delete select nodes%>" />
		<input class="btn cbi-button" type="button" id="select_all_btn" onclick="checked_all_node(this)" value="<%:Select all%>" />
		<input class="btn cbi-button cbi-button-apply" type="submit" name="cbi.apply" value="<%:Save & Apply%>" />
		<input class="btn cbi-button cbi-button-save" type="submit" name="cbi.save" value="<%:Save%>" />
		<input class="btn cbi-button cbi-button-reset" type="button" value="<%:Reset%>" onclick="location.href='<%=REQUEST_URI%>'" />
	</div>
</div>

<style>
	.pw-toolbar {
		width: 100%;
		text-align: center;
	}

	.pw-toolbar-field {
		width: 100%;
		text-align: center;
		display: inline-block;
		padding: 5px 0 5px;
	}

	#add_link_div {
		display: none;
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		background: white;
		padding: 20px;
		border: 2px solid #ccc;
		box-shadow: 0 0 10px rgba(0,0,0,0.5);
		z-index: 1000;
		width: 90%;
		max-width: 500px;
	}

	#add_link_modal_container {
		width: 100%;
		text-align: center;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-bottom: 20px;
	}

	#nodes_link {
		width: 100%;
		height: 180px;
		resize: vertical;
		font-family: monospace;
		padding: 5px;
		border: 1px solid #ccc;
		border-radius: 5px;
	}

	#nodes_link_text {
		color: red;
		font-size: 14px;
		margin-top: 5px;
		text-align: center;
		width: 100%;
	}

	#add_link_button_container {
		display: flex;
		justify-content: space-between;
		width: 100%;
		max-width: 300px;
		margin-top: 10px;
	}

	.value-custom {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;
		margin: 10px 0;
		padding: 0px 5px 0px 5px;
	}

	.value-field-custom {
		display: inline-flex;
		align-items: center;
		gap: 10px;
	}

	.value-title-custom {
		font-size: 13px;
		line-height: 28px;
		white-space: nowrap;
		text-align: right;
	}

	.custom-dropdown {
		position: relative;
		border: 1px solid #d9d9d9;
		border-radius: 2px;
		width: 180px;
		height: 28px;
		font-size: 13px;
		background: #fff;
		cursor: pointer;
		box-sizing: border-box;
		display: flex;
		align-items: center;
	}

	.selected-display {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 8px;
		width: 100%;
		height: 100%;
		box-sizing: border-box;
	}

	.selected-display:hover {
		background-color: #f7f7f7;
	}

	.selected-display .arrow {
		font-size: 12px;
		color: #666;
	}

	.dropdown-list {
		position: absolute;
		top: 100%;
		left: 0;
		width: 180px;
		border: 1px solid #d9d9d9;
		border-top: none;
		box-shadow: 0 1px 3px rgba(0,0,0,0.15);
		background: #fff;
		list-style: none;
		margin: 0;
		padding: 0;
		max-height: 200px;
		overflow-y: auto;
		overflow-x: hidden;
		z-index: 100;
		box-sizing: border-box;
	}

	.dropdown-item {
		padding: 4px 8px;
		line-height: 20px;
		cursor: pointer;
	}

	.dropdown-item.selected {
		background-color: #1e90ff;
		color: #fff;
	}

	.create-item-input::placeholder {
		text-align: center;
	}

	.dropdown-item.custom-input input {
		width: 100%;
		box-sizing: border-box;
		padding: 3px;
		font-size: 13px;
		line-height: 20px;
		border: 1px solid #ccc;
		text-align: left;
	}
</style>
